package com.demo.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;

/**
 * @Author: shubin_yao
 * @Date: 2022/05/02/8:13
 * @Description:
 *
 * 读写分离思想：
 * 读共享：读-读可共存
 * 写互斥：读-写互斥、写-写互斥
 *
 */
public class MyReadWiteLock {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    myCache.write();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    myCache.read();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
}

class MyCache{

    ReadWriteLock lock = new ReentrantReadWriteLock();

    //写时互斥
    public void write() throws InterruptedException {
        lock.writeLock().lock();
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println("写入数据:\t"+ i);
                TimeUnit.MILLISECONDS.sleep(300);
                System.out.println("写入数据:\t"+ i+"完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }


    //读时共享
    public void read() throws InterruptedException {
        lock.readLock().lock();
        try {
            for (int i = 0; i < 3; i++) {
                System.out.println("读出数据:\t"+ i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }

    }


}
